<template>
  <uni-popup ref="popup" type="bottom">
    <view class="bgWite">
      <view class="colse" @click="close">
        <uni-icons type="closeempty" size="20"></uni-icons>
      </view>
      <view class="detailHeader flex">
        <image v-if="data_xuan.goods_image" :src="getImgUrl(data_xuan.goods_image)"  mode="scaleToFill" />
        <image v-else :src="getImgUrl(dataInfo.shopInfo.goods_cover)"  mode="scaleToFill" />
        <view class="titleInfo flex flex-direction flex-bt">
          <view class="price "><text v-if="dataInfo.goodTypeData?.id==1">￥</text>{{data_xuan.price_selling||shopInfo.price_selling}}<text v-if="dataInfo.goodTypeData?.id!=1">{{ dataInfo.goodTypeData?.name }}</text></view>
          <view class="guige" v-if="dataInfo.shopInfo.spec_type==1">已选 : {{selectedPropTitle}}</view>
        </view>
      </view>
      <view class="scrollView" v-if="dataInfo.shopInfo.spec_type==1">
        <view class="detailGuige" v-for="(item,index) in dataInfo.shopInfo.goods_specs" :key="index">
          <view class="guigeTitle">
            <view class="title">{{item.name}}</view>
          </view>
          <view class="guigeList flex flex-line">
            <view class="list  flex flex-align flex-center" @click="selectActive(val.name,index,ins)" v-bind:class="[val.active?'':'noneActive',val.isShow?'active':'']" v-for="(val,ins) in item.list" :key="ins">
              {{val.name}}
            </view>
          </view>
        </view>
      </view>
      <view class="detailNum flex flex-align flex-bt">
        <view class="left">
          <view class="num">选择数量</view>
          <view class="kucun">销量{{sales||dataInfo.shopInfo.sales}},剩余库存{{surplus_stock||dataInfo.shopInfo.surplus_stock}}件</view>
        </view>
        <view class="right flex flex-align">
          <view class="jian flex flex-align flex-center" @click.stop="jianNum">-</view>
          <input type="number" v-model="number">
          <view class="add flex flex-align flex-center" @click.stop="addNum">+</view>
        </view>
      </view>
      <!-- <view class="detailQuan" @click="openQuan" v-if="dataInfo.shopInfo.return_coupon">
        <view class="flex flex-align flex-bt">
          <view class="left">
            <view class="title">赠送卡券</view>
          </view>
          <view class="right flex flex-align">
            <view class="xuanActive one-omit">{{dataInfo.shopInfo.return_coupon[0].name}}</view>
            <uni-icons type="right" size="20"></uni-icons>
          </view>
        </view>
      </view> -->
      <view class="submite" @click="submite">
        {{ dataInfo.goodTypeData?.id==1 ? '立即购买' : '立即兑换' }}
        
      </view>
    </view>
  </uni-popup>
  <!-- <quanList ref="quanListRef"></quanList> -->
</template>



<script setup lang="ts">
import { onMounted, ref, reactive, unref, computed } from 'vue'
import quanList from './quanList.vue';
import { getImgUrl, menuJump, toast } from '@/utils/tools';
import { goodStorage } from '@/utils/goodStorage';
const dataInfo= defineProps({
  show: {
    type: Boolean,
    default: true
  },
  shopInfo: {
    type: Object,
    default: () => {}
  },
  shopItemInfo: {
    type: Object,
    default: () => {}
  },
  goodTypeData: {
    type: Object,
    default: () => {} 
  }
})
setTimeout(()=>{
  if (dataInfo.shopInfo.goods_specs) {
    dataInfo.shopInfo.goods_specs.map((item:any)=>{
      item.list.map((val:any)=>{
        val.active = false
      })
    }) 
  }
},1000)
// 已选
const selectedPropTitle = ref('')
function selectedProp() {
  selectedPropTitle.value = ''
  unref(dataInfo).shopInfo.goods_specs.map((item:any)=>{
    item.list.map((val:any)=>{
      if(val.isShow){
        selectedPropTitle.value += val.name+','
      }
    })
  })
  if (selectedPropTitle.value.endsWith(',')) {
    selectedPropTitle.value = selectedPropTitle.value.slice(0, -1);
  }
  emit('submit', selectedPropTitle.value)
}
const selectArr:any = []
const subIndex:any = []
const data_xuan = ref<Recordable>({})
const sales = ref(0)
const surplus_stock = ref(0)
let showAttr:any = ''
const selectActive = (item: any,n:number,index:number)=>{
  if (selectArr[n] != item) {
      selectArr[n] = item;
      subIndex[n] = index;
      dataInfo.shopInfo.goods_specs[n].list.map((val:any,inds:number)=>{
        if(index==inds){
          val.isShow = true
        }else{
          val.isShow = false
        }
      })
    } else {
      selectArr[n] = undefined;
      subIndex[n] = -1; //去掉选中的颜色
      data_xuan.value = {}
      dataInfo.shopInfo.goods_specs[n].list[index].isShow = false;
    }
    
    var showarr =selectArr;
    var tempTop: any[] = [];
    showarr.forEach((item: any, i: any, arr: any) => {
      if (item) {
        tempTop.push(item)
      }
    })
      
    showAttr = tempTop.join(";");
    getGuige();
    tempTop = []
  selectedProp()
}
function getGuige(){
  var result: any[] = []; //定义数组存储被选中的值
  dataInfo.shopInfo.goods_specs.map((item:any,index:  number)=>{
    result[index] = selectArr[index] ? selectArr[index] : '';
  })
  
  if (dataInfo.shopItemInfo[result.join(":")]) {
    data_xuan.value = dataInfo.shopItemInfo[result.join(":")]
  }
  for (var i in dataInfo.shopInfo.goods_specs) {
    var last = result[i]; //把选中的值存放到字符串last去
    for (var k in dataInfo.shopInfo.goods_specs[i].list) {
      result[i] = dataInfo.shopInfo.goods_specs[i].list[k].name; //赋值，存在直接覆盖，不存在往里面添加name值
      dataInfo.shopInfo.goods_specs[i].list[k].active = isMay(result); //在数据里面添加字段isShow来判断是否可以选择
    }
    result[i] = last; //还原，目的是记录点下去那个值，避免下一次执行循环时避免被覆盖
  }
  sales.value = data_xuan.value.sales
  surplus_stock.value = data_xuan.value.surplus_stock
}
function isMay(result: any) {
  for (var i in result) {
    if (result[i] == '') {
      return true; //如果数组里有为空的值，那直接返回true
    }
  }
  if (dataInfo.shopItemInfo[result.join(":")]) { //匹配选中的数据的库存，若不为空返回true反之返回false
    return dataInfo.shopItemInfo[result.join(":")].surplus_stock==0 ? false : true;
  }
}
const emit = defineEmits(['submit', 'update:show'])
const quanListRef = ref<InstanceType<typeof quanList>>()
const number = ref(1)
onMounted(() => {})
const popup = ref<any>(null)
async function open() {
  popup.value?.open('bottom')
  if(dataInfo.shopInfo.spec_type==1){
    setTimeout(()=>{
      getGuige()
    },500)
  }else{
    data_xuan.value = dataInfo.shopInfo.goods_specs_item[0]
    sales.value = data_xuan.value.sales
    surplus_stock.value = data_xuan.value.surplus_stock
  }
  updateShow(true)
}
async function openQuan(){
  quanListRef.value?.open()
  updateShow(true)
}
function close() {
  popup.value?.close()
 
  updateShow(false)
}
function addNum(){
  number.value++
}
function jianNum(){
  if(number.value>1){
    number.value--
  }
}
function submite(){
  let dataInfos = {
    code:'',
    goods_cover:'',
    goods_name:'',
    price_selling:'',
    number:1,
    spec_type:1,
    goods_spec:'',
    goods_tag:'',
    return_coupon:[],
    goods_item_id:'',
    postage:'',
    goodTypeData:{},
    use_coupon_num:0,
    max_coupon_deduction:0,
  }
  dataInfos.code = dataInfo.shopInfo.id
  dataInfos.goods_cover = data_xuan.value.goods_image
  dataInfos.goods_name = dataInfo.shopInfo.goods_name
  dataInfos.price_selling = data_xuan.value.price_selling
  dataInfos.number= number.value
  dataInfos.spec_type= dataInfo.shopInfo.spec_type
  dataInfos.goods_tag = dataInfo.shopInfo.goods_tag
  dataInfos.return_coupon = dataInfo.shopInfo.return_coupon
  dataInfos.goods_item_id = data_xuan.value.id
  dataInfos.postage = dataInfo.shopInfo.postage
  dataInfos.goodTypeData = dataInfo.goodTypeData
  dataInfos.goods_spec = selectedPropTitle.value
  dataInfos.use_coupon_num = dataInfo.shopInfo.use_coupon_num
  dataInfos.max_coupon_deduction = dataInfo.shopInfo.max_coupon_deduction
  if(dataInfo.shopInfo.spec_type==1){
    if(Object.keys(data_xuan.value).length === 0){
      uni.showToast({
        title: '请选择规格',
        icon: 'none',
        duration: 1000
      })
      return
    }else if(data_xuan.value.surplus_stock==0||number.value>data_xuan.value.surplus_stock){
      uni.showToast({
        title: '库存不足',
        icon: 'none',
        duration: 1000
      })
      return
    }else{
      goodStorage.set('routerInfo', dataInfos)
      menuJump({is_tab: false,link: '/pages/shop/submiteOrder',link_type: 1})
      close()
    }
    
  }else{
    goodStorage.set('routerInfo', dataInfos)
    menuJump({is_tab: false,link: '/pages/shop/submiteOrder',link_type: 1})
    close()
  }
  
}
function updateShow(value: boolean) {
  emit('update:show', value)
}
defineExpose({
  open
})
</script>

<style lang="scss" scoped>
.bgWite{background: #fff;max-height: 1000rpx;border-radius: 30rpx 30rpx 0 0;position: relative;
  padding-bottom: 30rpx;
  .colse{position: absolute;right: 30rpx;top:30rpx;}
  .detailHeader{padding: 30rpx;
    image{width: 144rpx;height: 144rpx;margin-right: 10rpx;}
    .titleInfo{
      .price{color: #FF4927;font-size: 44rpx;font-weight: bold;
        text{font-size: 32rpx;}
      }
      .guige{color: #323233;font-size: 28rpx;}
    }
  }
  .detailGuige{margin: 0rpx 0 40rpx;
   .guigeTitle{padding: 0 30rpx;
     .title{font-size: 28rpx;color: #323233;font-weight: bold;}
   }
   .guigeList{
    .list{padding:10rpx 30rpx;background: #F5F6F7;color: #323233;border-radius: 40rpx;margin-left: 20rpx;margin-top: 20rpx;border: 1px solid #F5F6F7;}
    .list.active{background: #FFE8DD;border: 1px solid #FE7431;color: #FE7431;}
    .list.noneActive{
					background-color: #ccc;
					opacity: 0.4;
					color: #000;
					pointer-events: none;
				}
    }
  }
  .detailNum{padding: 0 30rpx 30rpx;
    .left{
     .num{font-size: 28rpx;color: #323233;font-weight: bold;}
    .kucun{font-size: 24rpx;color: #FE7431;margin-top: 6rpx;}
    }
    .right{
      .jian{width: 48rpx;height: 48rpx;background: #FE7431;color: #fff;font-size: 32rpx;border-radius: 48rpx;font-weight: bold;margin-right: -24rpx;position: relative;z-index: 11;}
      .add{width: 48rpx;height: 48rpx;background: #FE7431;color: #fff;font-size: 32rpx;border-radius: 48rpx;font-weight: bold;margin-left: -24rpx;position: relative;z-index: 11;}
      input{width: 108rpx;height: 48rpx;background: #F5F6F7;font-size: 24rpx;text-align: center;}
    }
  }
  .detailQuan{margin: 0rpx 0 40rpx;
    .flex{padding: 0 10rpx 0 30rpx;
      .left{
        .title{font-size: 28rpx;color: #323233;font-weight: bold;}
      }
      .right{
        uni-icons{color: #969799;}
        .xuanActive{color: #FE7431;width: 400rpx;text-align: right;}
      }
    }
  }
  .submite{
   height: 80rpx;background: #FE7431;color: #fff;font-size: 32rpx;font-weight: bold;border-radius: 80rpx;display: flex;justify-content: center;align-items: center;
    font-size: 26rpx;margin: 20rpx 30rpx 30rpx;
  }
  .scrollView{max-height: 700rpx;overflow-y: auto;}
}
</style>
